function i_serie=monthyl_nemo_mean(serie,time)

% ----------------------------------------------
% Function to compute monthly mean from NEMO
% output (5-days means).
%
% this function take into account dates closed to
% the begin or the end of each month.
%
%
% - Input:
%
% serie: model fields to average - dimensions: lon,lat,time
% time: time vector in "matlab" time.

V=datevec(time);

i_serie(1:size(serie,1),1:size(serie,2),1:12)=NaN;

% - Aim to find indices (in time vector) for average over each month
for im=1:12
    ind=find(V(:,2)==im);
        
    
    % - Multiplication coefficeint to recompute the weighted average
    co(1:length(ind))=median(diff(time));
    
    % - Add a weight on indices close to another month
    % i.e. considering only 3 days of the first average instead of 5 days.
    if (V(ind(1),3) < 5) % - First month date lower than 5th
        co(1)=V(ind(1),3);
    end
    
    if ((ind(end)+1 <= length(time)) && ( V(ind(end)+1,3) < 5 ) )  
        % - more than 1 day between the last date and the first day of the next month (i.e. not 31rst)
        
        % - we add the next file
        ind=[ind;ind(end)+1];
        co(end+1)=5-V(ind(end),3);
    end
        
    % - Average fields    
    nbd=sum(co);
    co=repmat(co,[size(serie,1),1,size(serie,2)]);
    co=permute(co,[1 3 2]);
    i_serie(:,:,im)=nansum(serie(:,:,ind).*co,3)./nbd;
    
    co=[];
    clear co
    
end

   
